package com.system.permissiondemo.service.impl;

import com.google.common.base.Preconditions;
import com.system.permissiondemo.beans.PageQuery;
import com.system.permissiondemo.beans.PageResult;
import com.system.permissiondemo.common.RequestHolder;
import com.system.permissiondemo.dto.UserDTO;
import com.system.permissiondemo.entity.SysDept;
import com.system.permissiondemo.entity.SysUser;
import com.system.permissiondemo.mapper.SysDeptMapper;
import com.system.permissiondemo.mapper.SysUserMapper;
import com.system.permissiondemo.param.UserParam;
import com.system.permissiondemo.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 用户新增
     * @param param
     */
    @Override
    public void save(UserParam param) {
        if (checkEmailExist(param.getMail(),param.getId())){
            throw new ClassCastException("邮箱已被占用");
        }
        if (checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ClassCastException("电话已被占用");
        }
        String password = "123456";
        SysUser user = SysUser.builder()
                        .username(param.getUsername())
                        .telephone(param.getTelephone())
                        .mail(param.getMail())
                        .deptId(param.getDeptId())
                        .remark(param.getRemark())
                        .status(param.getStatus())
                        .password(password).build();
        user.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        user.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        user.setOperatorTime(new Date());
        // TODO: 发送 email 通知用户
        sysUserMapper.insertSelective(user);

    }

    /**
     * 更新用户
     * @param param
     */
    @Override
    public void update(UserParam param) {
        //检查邮箱是否已经存在
        if (checkEmailExist(param.getMail(),param.getId())){
            throw new ClassCastException("邮箱已被占用");
        }
        //检查电话是否已经存在
        if (checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ClassCastException("电话已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");
        SysUser after = SysUser.builder()
                        .id(param.getId())
                        .username(param.getUsername())
                        .telephone(param.getTelephone())
                        .mail(param.getMail())
                        .deptId(param.getDeptId())
                        .remark(param.getRemark())
                        .status(param.getStatus())
                        .password(before.getPassword()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        after.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        after.setOperatorTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
    }

    /**
     * 依据邮箱或电话进行查询用户
     * @param keyword
     * @return
     */
    @Override
    public SysUser findByKeyword(String keyword) {
        return sysUserMapper.findByKeyword(keyword);
    }

    @Override
    public Integer deleteById(Integer userId) {
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        if (user!=null){
            sysUserMapper.deleteByPrimaryKey(user.getId());
        }
        return null;
    }

    /**
     * 根据分页和部门id获取用户列表
     * @param deptId
     * @param page
     * @return
     */
    @Override
    public PageResult<UserDTO> getPageByDeptId(Integer deptId, PageQuery page) {
        Integer count = sysUserMapper.countByDeptId(deptId);
        List<UserDTO> userDTOS = new ArrayList<>();
        if (count > 0){
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId,page);
            for (int i = 0; i < list.size(); i++) {
                SysUser user = list.get(i);
                UserDTO userDTO = new UserDTO();
                BeanUtils.copyProperties(user,userDTO);
                userDTO.setStatusName(getStatus(user.getStatus()));
                SysDept dept = deptMapper.selectByPrimaryKey(user.getDeptId());
                if (dept!=null){
                    userDTO.setDeptName(dept.getName());
                }
                userDTOS.add(userDTO);

            }
            return PageResult.<UserDTO>builder().total(count).data(userDTOS).build();
        }
        return PageResult.<UserDTO>builder().build();

    }


    /**
     * 根据状态值，返回状态描述
     * @param status
     * @return
     */
    private String getStatus(Integer status){
        if (status==0){
            return "冻结";
        }else if (status==1){
            return "正常";
        }else {
            return "删除";
        }
    }

    /**
     * 邮箱是否存在
     * @param mail
     * @param userId
     * @return
     */
    private boolean checkEmailExist(String mail, Integer userId){
        return sysUserMapper.countByMail(mail,userId)>0;
    }

    /**
     * 电话是否存在
     * @param Telephone
     * @param userId
     * @return
     */
    private boolean checkTelephoneExist(String Telephone, Integer userId){
        return sysUserMapper.countByTelephone(Telephone,userId)>0;
    }
}
